package cn.evun.tms.generator.task;

import cn.evun.tms.generator.Constants;
import cn.evun.tms.generator.config.Configuration;
import cn.evun.tms.generator.framework.AbstractApplicationTask;
import cn.evun.tms.generator.framework.context.ApplicationContext;
import cn.evun.tms.generator.handler.BaseHandler;
import cn.evun.tms.generator.handler.impl.EntityHandler;
import cn.evun.tms.generator.model.DaoInfo;
import cn.evun.tms.generator.model.DtoInfo;
import cn.evun.tms.generator.model.EntityInfo;
import cn.evun.tms.generator.util.PropertyUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class EntityTask extends AbstractApplicationTask {

	private static String ENTITY_FTL = "template/Entity.ftl";

	private List<EntityInfo> entityInfos;

	@SuppressWarnings("unchecked")
	@Override
	protected boolean doInternal(ApplicationContext context) throws Exception {
		logger.info("开始生成实体");

		// 获取实体信息
		entityInfos = (List<EntityInfo>) context.getAttribute("entityInfos");

		BaseHandler<EntityInfo> handler = null;
		for (EntityInfo entityInfo : entityInfos) {
			handler = new EntityHandler(ENTITY_FTL, entityInfo);
			handler.execute(context);
		}
		logger.info("生成实体类完成");
		return false;
	}

	@Override
	protected void doAfter(ApplicationContext context) throws Exception {
		super.doAfter(context);

		List<DaoInfo> daoList = new ArrayList<DaoInfo>();
		List<DtoInfo> dtoList = new ArrayList<DtoInfo>();
		// 组装Dao信息、组装Vo信息
		DaoInfo daoInfo = null;
		DtoInfo dtoInfo = null;
		for (EntityInfo entityInfo : entityInfos) {
			dtoInfo = new DtoInfo();
			dtoInfo.setPackageStr(Configuration.getString("dto.package"));
			dtoInfo.setClassName(entityInfo.getEntityName() + Constants.VO_SUFFIX);
			dtoInfo.setEntityInfo(entityInfo);
			dtoList.add(dtoInfo);
			daoInfo = new DaoInfo();
			daoInfo.setClassName(entityInfo.getEntityName() + Constants.DAO_SUFFIX);
			daoInfo.setEntityInfo(entityInfo);
			daoInfo.setDtoInfo(dtoInfo);
			daoInfo.setImportStr("import " + Configuration.getString("entity.package") + Constants.CHARACTER_POINT
					+ entityInfo.getClassName() + Constants.CHARACTER_SPLIT);
			daoInfo.setImportStrDto("import " + Configuration.getString("dto.package") + Constants.CHARACTER_POINT
					+ dtoInfo.getClassName() + Constants.CHARACTER_SPLIT);
			daoInfo.setPackageStr(Configuration.getString("dao.package"));
			daoList.add(daoInfo);

		}

		context.setAttribute("daoList", daoList);
		context.setAttribute("dtoList", dtoList);
	}

	public static void main(String[] args) {
		File file = new File(
				"/D:\\devsoftware\\workspace\\winit-java-generator\\target\\classes\\template\\Entity.ftl");
		System.out.println(EntityTask.class.getClassLoader().getResource("").getPath());
		System.out.println(file.exists());

		PropertyUtil.setProperty("name", "qyk1");
		PropertyUtil.setProperty("NAME", "qyk22");
	}

}
